package com.example.administrator.jim.addresslist;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.jim.BaseActivity;
import com.example.administrator.jim.MainActivity;
import com.example.administrator.jim.R;
import com.example.administrator.jim.bean.UserInfoBean;
import com.sdsmdg.tastytoast.TastyToast;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import agency.tango.android.avatarview.IImageLoader;
import agency.tango.android.avatarview.loader.PicassoLoader;
import agency.tango.android.avatarview.views.AvatarView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.model.UserInfo;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by BarBrothers on 2017/12/27.
 */

public class AddFriendActivity extends BaseActivity {
    @BindView(R.id.addfriendactivity_title_mine_huitui)
    ImageView mAddfriendactivityTitleMineHuitui;
    @BindView(R.id.addfriendactivity_title_textview)
    TextView mAddfriendactivityTitleTextview;
    @BindView(R.id.mainactivity_title)
    RelativeLayout mMainactivityTitle;
    @BindView(R.id.addfriendactivity_et_search)
    EditText mAddfriendactivityEtSearch;
    @BindView(R.id.addfriendactivity_search)
    TextView mAddfriendactivitySearch;
    @BindView(R.id.addfriendactivity_avatat)
    AvatarView mAddfriendactivityAvatat;
    @BindView(R.id.addfriendactivity_usernikname)
    TextView mAddfriendactivityUsernikname;
    @BindView(R.id.addfriendactivity_item_searchfriend)
    RelativeLayout mAddfriendactivityItemSearchfriend;
    IImageLoader imageLoader;
    private UserInfoBean mUserInfoBean;
    private UserInfo mUserInfo;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addfriend);
        getSupportActionBar().hide();
        setClazz(AddFriendActivity.class);
        ButterKnife.bind(this);
        initDatas();
        initListener();
    }

    private void initListener() {
        mAddfriendactivityEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mAddfriendactivityItemSearchfriend.setVisibility(View.GONE);
            }
        });
    }
    private void initDatas() {
        imageLoader = new PicassoLoader();
    }
    @OnClick({R.id.addfriendactivity_title_mine_huitui, R.id.addfriendactivity_search,R.id.addfriendactivity_item_searchfriend})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.addfriendactivity_title_mine_huitui:
                finish();
                break;
            case R.id.addfriendactivity_search:
                Observable.create(new ObservableOnSubscribe<UserInfoBean>() {
                    @Override
                    public void subscribe(final ObservableEmitter<UserInfoBean> e) throws Exception {
                        String username = mAddfriendactivityEtSearch.getText().toString().trim();
                        JMessageClient.getUserInfo(username, new GetUserInfoCallback() {
                            @Override
                            public void gotResult(int i, String s, UserInfo userInfo) {
                                if(i==0){
                                    mUserInfo=userInfo;
                                    final UserInfoBean user=new UserInfoBean();
                                    user.setNikkname(userInfo.getNickname());
                                    user.setBeizhu(userInfo.getNotename());
                                    if(userInfo.getBirthday()>0){
                                        user.setBirthdry(paseTime(userInfo.getBirthday()));
                                    }else {
                                        user.setBirthdry("");
                                    }
                                    user.setUsername(userInfo.getUserName());
                                    user.setGexingqianm(userInfo.getSignature());
                                    if(String.valueOf(userInfo.getGender()).equals("male")) {
                                        user.setGender("男");
                                    }else if(userInfo.getGender().equals("female")) {
                                        user.setGender("女");
                                    }else {
                                        user.setGender("保密");
                                    }
                                    user.setDiqu(userInfo.getAddress());
                                    userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                                        @Override
                                        public void gotResult(int i, String s, Bitmap bitmap) {
                                            user.setBitmap(bitmap);
                                            e.onNext(user);
                                        }
                                    });
                                }else {
                                    TastyToast.makeText(getApplicationContext(), "该用户不存在", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
                                }
                            }
                        });
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<UserInfoBean>() {
                            @Override
                            public void accept(UserInfoBean userInfoBean) throws Exception {
                                mUserInfoBean=userInfoBean;
                                if(userInfoBean.getNikkname().equals("")){
                                    mAddfriendactivityUsernikname.setText(userInfoBean.getUsername());
                                }else {
                                    mAddfriendactivityUsernikname.setText(userInfoBean.getNikkname());
                                }
                                if(userInfoBean.getBitmap()!=null){
                                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                    userInfoBean.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                                    byte[] bytes= byteArrayOutputStream.toByteArray();
                                    Glide.with(AddFriendActivity.this)
                                            .load(bytes)
                                            .into(mAddfriendactivityAvatat);
                                }else if(MainActivity.mMyInfo.getNickname().equals("")){
                                    imageLoader.loadImage(mAddfriendactivityAvatat,null, userInfoBean.getUsername(), 50);
                                }else {
                                    imageLoader.loadImage(mAddfriendactivityAvatat,null, userInfoBean.getNikkname(), 50);
                                }
                                mAddfriendactivityItemSearchfriend.setVisibility(View.VISIBLE);
                                }
                        });
                break;
            case R.id.addfriendactivity_item_searchfriend:
                boolean friend = mUserInfo.isFriend();
                Intent intent=new Intent(this,UserInfoDescActivity.class);
                intent.putExtra("isfriend",friend);
                mUserInfoBean.setBitmap(null);
                intent.putExtra("userinfo",mUserInfoBean);
                startActivity(intent);
                break;
        }
    }
    //转换时间为年月日显示
    private String paseTime(long time) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= new Date(time);
        return format.format(date);
    }
}
